using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using TlsService;
using UnityEngine;

public class SingleRecord
{
    public Tls tls;
    private AudioClip recordingClip;
    private bool bRecording;
    private const int rate = 16000;
    private const int recordSeconds = 10;
    private const int packetSize = 6400;
    private const int interval = 20;
    public SingleRecord()
    {
        tls = new Tls();
    }
    
    public async void StartRecord()
    {
        if(Microphone.devices.Length<=0) return;
        recordingClip = Microphone.Start(null, false, recordSeconds, rate);
        while (Microphone.GetPosition(null)<=0)
        {
            await Task.Yield();
        }

        bRecording = true;
        tls.Open();
    }

    public async void StopRecord()
    {
        if(bRecording == false) return;
        
        Microphone.End(null);
        float[] samples = new float[recordingClip.samples];
        recordingClip.GetData(samples, 0);
        var audioBuffer = ConvertFloatArrayToByteArray(samples);
        
        int packetCount = (int)Math.Ceiling((double)audioBuffer.Length / packetSize);
        
        for (int i = 0; i < packetCount; i++)
        {
            await Task.Delay(interval);
            int offset = i * packetSize;
            int count = Math.Min(packetSize, audioBuffer.Length - offset);
            byte[] packet = new byte[count];
            Array.Copy(audioBuffer, offset, packet, 0, count);
            tls.SendAudioStream(packet);
        }
        tls.SendEndStream();
    }
    private byte[] ConvertFloatArrayToByteArray(float[] floatArray)
    {
        byte[] byteArray = new byte[floatArray.Length * 2];
        for (int i = 0; i < floatArray.Length; i++)
        {
            short shortValue = (short)(floatArray[i] * 32767); // 将浮点数转换为short值
            byte[] bytes = BitConverter.GetBytes(shortValue);
            Array.Copy(bytes, 0, byteArray, i * 2, 2);
        }
        return byteArray;
    }
    
}
